package club.dmyang.shiro;

import club.dmyang.entity.Permission;
import club.dmyang.entity.Role;
import club.dmyang.entity.User;
import club.dmyang.service.RoleService;
import club.dmyang.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

/**
 * Created by brss on 2018/6/29.
 */
public class UserRealm extends AuthorizingRealm{

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //给资源添加授权资源 字符串
        //info.addStringPermission("add");

        //获取principal（用户名）
        //下方传入（第一个参数）：SimpleAuthenticationInfo autheInfo = new SimpleAuthenticationInfo(user.getName(), user.getPassword(), "UserRealm");
        Subject subject = SecurityUtils.getSubject();
        String name = (String) subject.getPrincipal();//获取当前用户的   用户名

        User user = userService.queryUserByName(name);//根据用户名查询用户（联查了该用户的角色）
        for ( Role r : user.getRoleList() ){
            Role role = roleService.queryRoleByRoleName(r.getRname());//根据角色名查询该角色（联查了该角色的所有权限）
            r.setPermsList(role.getPermsList());//把查到的权限列表装入到user.roleList.permsList中去
        }

        //对该用户授权
        Set<String> perms = new HashSet<String>();
        for (Role r : user.getRoleList() ){
            for (Permission p : r.getPermsList()) {
                perms.add(p.getName());//把该用户所拥有的权限装入到set容器中
            }
        }
        info.addStringPermissions(perms);
        return info;
    }

    /**
     * 执行认证逻辑
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("认证");
        //编写Shiro判断逻辑，判断用户名和密码是否正确
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        //1.判断用户名
        User user = userService.queryUserByName(token.getUsername());
        if ( user == null) {
            //用户名不存在
            return null;//shiro 底层会抛出UnknownAccountException
        }
        //2.判断密码：
        //第一个参数：principal意思主要的，相当与主键的意思，第二个参数：数据库密码，第三个参数：realm的名字
        SimpleAuthenticationInfo autheInfo = new SimpleAuthenticationInfo(user.getName(), user.getPassword(), "UserRealm");
        return autheInfo;
    }
}
